"ui";
/*
 * @Author: 白酒煮饭 
 * @Date: 2019-03-09 15:48:35 
 * @Last Modified by: QQ1641763174
 * @Last Modified time: 2019-03-11 19:55:19
 */
importPackage(android.speech.tts);
importClass(java.util.Locale);
importClass(java.io.File);
let tts = new TextToSpeech(context, function(status) {
    if (status != tts.SUCCESS) {
        toast("初始化TTS识别: " + status);
        exit();
    }
    let r = tts.setLanguage(Locale.CHINA);
    if (r < 0) {
        toast("不支持该语言: " + r);
        exit();
    }
});
tts.setOnUtteranceProgressListener(new UtteranceProgressListener({
    onDone: function(id) {}
}));

ui.layout(
    <frame>
        <vertical>
            <horizontal>
                <img id="exit" src="file://./res/ic_keyboard_backspace_black_48dp.png" w="40" h="40" gravity="center"/>
                <text text="文字转语音设置"  textColor="#333333" textSize="27sp" typeface="serif" gravity="top|center" w="*" textStyle="bold"/>
            </horizontal>
            <Switch id="autoService" text="无障碍服务" checked="{{auto.service != null}}" padding="8 8 8 8" textSize="15sp" textSize="18sp"/>            
            <horizontal margin="5 0 5 5">
                <text text="选择版本:" size="60px" gravity="right|center"/>
                <radiogroup w="*" marginLeft="20px"id="id_1" orientation="horizontal">
                    <radio checked="true"size="50px" text="QQ"/>
                    <radio checked="false"size="50px" text="TIM"/>
                </radiogroup>
            </horizontal>
            <horizontal margin="5 0 2 10">
                <text text="发音引擎:" size="60px" gravity="left|center"/>
                <radiogroup w="*" marginLeft="20px"id="id_2" orientation="horizontal">
                    <radio checked="true"size="50px" text="本地TTS"/>
                    <radio checked="false"size="50px" text="百度"/>
                </radiogroup>
            </horizontal>
            <horizontal margin="5 0 2 10">
                <text text="声音:" size="60px" gravity="left|center"/>
                <radiogroup w="*" marginLeft="20px"id="id_3" orientation="horizontal">
                    <radio checked="true"size="50px" text="女声"/>
                    <radio checked="false"size="50px" text="男声"/>
                </radiogroup>
            </horizontal>
            
            <horizontal  margin="5 30 5 30" bg="#d3d3d3">
                <text text="QQ号：" size="30" />
                <text id="in_1" layout_weight="1" textSize="60px" hint="点击右侧选择按钮" bg="#d3d3d3" inputType="number" maxLength="10"/>
                <button id="bu_1" text="选择" gravity="center"/>
            </horizontal>
            <text text="使用说明:" textSize="19dx" gravity="center"/>
            <text text="该功能可以在获取输入框文本，转换成语音，然后发送给好友或群。使用方法：在此界面选择对应的QQ版本及QQ号，QQ号码一定要选择正在使用的QQ号码，要不然会无法发送。" paddingLeft="16dx" paddingRight="16px"/>
        </vertical>
        <button text="开始运行" layout_gravity="bottom" id="btn_start" style="Widget.AppCompat.Button.Colored"w="*"h="180px"/>
    </frame>
);
var QQ_id, TTS_id, Sex_id, QQ, mt;
var QQsFile = {
    "QQ": ["MobileQQ", ".slk"],
    "TIM": ["Tim", ".amr"],
    "QQ轻聊版": ["QQLite", ".amr"]
    }
var QQs = Object.keys(QQsFile);
var stg = storages.create("qqtts0");
QQ_id = stg.get("QQ_id");
TTS_id = stg.get("TTS_id");
Sex_id = stg.get("sex");
QQ = stg.get("uin");

if (stg != null && QQ_id != null && TTS_id != null && QQ != null && Sex_id != null) {
    ui.run(function() {
        ui.in_1.setText(QQ);
        ui.id_1.getChildAt(QQ_id).setChecked(true);
        ui.id_2.getChildAt(TTS_id).setChecked(true);
        ui.id_3.getChildAt(Sex_id).setChecked(true);
    });
}
ui.autoService.on("check", function(checked) {
    // 用户勾选无障碍服务的选项时，跳转到页面让用户去开启
    if(checked && auto.service == null) {
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        });
    }
    if(!checked && auto.service != null){
        auto.service.disableSelf();
    }
});

// 当用户回到本界面时，resume事件会被触发
ui.emitter.on("resume", function() {
    // 此时根据无障碍服务的开启情况，同步开关的状态
    ui.autoService.checked = auto.service != null;
});
ui.exit.on("click",()=>{ui.finish();});
ui.bu_1.on("click", function() {
    putData();
    QQ_Choice(QQ_id);
});

ui.btn_start.on("click", function() {
    if(auto.service == null) {
        toast("请先开启无障碍服务！");
        return;
    }
    if (ui.in_1.text().length > 5) {putData();
        if (!mt) {
            dialogs.confirm("提示", "是否立即前往对应APP？", (a) => {
                if (a) {
                    launchApp(QQs[QQ_id]);}
                //}else{home();}
            });
        }
        start();
    } else {
        toast("QQ号格式错误");
    }
});


function onClick() {
    if (currentActivity() == "com.tencent.mobileqq.activity.SplashActivity"||"com.tencent.mobileqq.activity.ChatActivity") {
        threads.start(function() {
            run(1);
        });
    } else {
        alert("请打开QQ聊天窗口")
     }
}

function run(r) {
    var r = r;
    while (r) {
        var name = "tmp.mp3"
        var path = "/sdcard/Android/"
        var str = id("input").findOne().text();
        if (str) {
            setText("文字转语音中……");
            if(TTS_id == 1){
                yu(str, path + name);
            }else{
                TTS(str, path + name);
            }    
            qqVoice(name, QQ, path);
        } else {
            alert("聊天文字输入框内容为空")
        }
        setText("");
        r = 0;
    }
}

function yu(str, path) {
    let TOKEN = http.get("https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=RcHrd7F0OVk9kA8O0tOZno9L&client_secret=r2nz7A5EulMisiU6VrWCQz8AXSn7wPGI").body.json().access_token;
    let json = {
        "lan": "zh",
        "ctp": "1",
        "cuid": "abcdxxx",//	用户唯一标识
        "tok": TOKEN,
        "tex": str,//合成的文本
        "vol": "12",//音量 0-15
        "per": Sex_id,// 发音人选择, 0为普通女声，1为普通男生，3为情感合成-度逍遥，4为情感合成-度丫丫，默认为普通女声
        "spd": "5",//语速 0-15
        "pit": "5"//音调 0-15
    }
    let file = http.post("http://tsn.baidu.com/text2audio?", json).body.bytes();
    files.writeBytes(path, file);
}

function TTS(TTS_Text, path) {
    //tts.speak(text, tts.QUEUE_ADD, null);
    let p = new File(path);
    tts.synthesizeToFile(TTS_Text, null, p, Math.random());
}
/**
 * qqVoice(name, QQ, originPath)
 * 调用方法：name为要发送语音的名称;QQ是你要用的QQ号;originpath是要发送语音的父文件夹的路径
 */
function qqVoice(name, QQ, originPath) {
    if (QQ == undefined) {
        toast("传入QQ号为空");
        return false;
    }
    if (originPath == undefined) {
        toast("传入路径为空");
        return false;
    }
    var date1 = (new Date().getYear() + 1900) * 100 + new Date().getMonth() + 1;
    var date2 = new Date().getDate();
    var path = "/sdcard/tencent/"+QQsFile[QQs[QQ_id]][0]+"/" + QQ + "/ptt/" + date1 + "/" + date2 + "/";
    sleep(200);toastLog(path);
    if (desc("开始录音").find().empty()) {
        accessibilityFocused(false).checked(false).className("android.widget.ImageView").clickable(true).column(-1).columnCount(0).column(-1).contextClickable(false).depth(9).dismissable(false).findOne().click();
    }
    sleep(200);
    click("录音");
    sleep(200);
    desc("开始录音").find().click();
    sleep(2650)
    desc("停止录音").find().click();
    toastLog(path);
    sleep(800);
    var fileName = max(files.listDir(path));
    files.remove(path + fileName);
    files.copy(originPath + name, path + name)
    files.rename(path + name, fileName);
    sleep(200);
    id("listen_panel_send_tv").find().click();
}

function max(array) {
    var a = 0;
    for (i = 0; i < array.length; i++) {
        re = /\d+/g;
        name = array[i].match(re, "g");
        if (name > a) {
            a = name
        }
    }
    return "stream_" + a + QQsFile[QQs[QQ_id]][1];
}

function floa(){
var window = floaty.window(
    <frame><linear>
        <button id="action" text="转换" w="40" h="40" color="#ffffff" bg="#66000000" />
    </linear> </frame>
);

var execution = null;

//记录按键被按下时的触摸坐标
var x = 0,
    y = 0;
//记录按键被按下时的悬浮窗位置
var windowX, windowY;
//记录按键被按下的时间以便判断长按等动作
var downTime;
window.action.setOnTouchListener(function(view, event) {
    switch (event.getAction()) {
        case event.ACTION_DOWN:
            x = event.getRawX();
            y = event.getRawY();
            windowX = window.getX();
            windowY = window.getY();
            downTime = new Date().getTime();
            return true;
        case event.ACTION_MOVE:
            //移动手指时调整悬浮窗位置
            window.setPosition(windowX + (event.getRawX() - x),
                windowY + (event.getRawY() - y));
            //如果按下的时间超过1.5秒判断为长按，退出脚本
            if (new Date().getTime() - downTime > 1500) {
                exit();
            }
            return true;
        case event.ACTION_UP:
            //手指弹起时如果偏移很小则判断为点击
            if (Math.abs(event.getRawY() - y) < 5 && Math.abs(event.getRawX() - x) < 5) {
                onClick();
            }
            return true;
    }
    return true;
});
}

function QQ_Choice(sun) {
    threads.start(function() {
        var SDRoot = "/sdcard/";
        if (files.exists(SDRoot + "Tencent/")) {
            tencentDirectory = "Tencent/";
        } else if (files.exists(SDRoot + "tencent/")) {
            tencentDirectory = "tencent/";
        } else {
            toast("在 " + SDRoot + " 目录下找不到 Tencent 文件夹，请确认您已安装QQ，且此目录为SD卡根目录");
            return false;
        }
        var QQFileName = QQsFile[QQs[sun]][0];
        var allQQFiles = files.listDir(SDRoot + tencentDirectory + QQFileName + "/");
        var QQUins = new Array();
        for (i in allQQFiles) {
            var fileName = allQQFiles[i];
            if (fileName.match(/^\d{5,20}(32552732){0}$/) != null) {
                QQUins.push(fileName);
            }
        }
        if (!QQUins.length) {
            toast("找不到QQ号码，请确认您当前使用的是您选择的版本，如仍有异常，请收发语音后再试");
            return false;
        }
        var QQUin = QQUins[dialogs.singleChoice("请选择您的QQ号码", QQUins)];
        if (!QQUin) {
            toast("请选择您的QQ号码，若找不到您的QQ号码，请重新选择您的QQ版本");
            return false;
        }
        ui.run(function() {
            ui.in_1.setText(QQUin);
        });
        stg.put("uin", QQUin);
    });
}
//返回radio控件第几个被选择
function selectedIndex(rg) {  
    let id = rg.getCheckedRadioButtonId();  
    for (let i = 0; i < rg.getChildCount(); i++) {    
        if (id == rg.getChildAt(i).getId()) {      
            return i;    
        }  
    }  
    return -1;
}

function putData(){
    QQ_id = selectedIndex(ui.id_1); //QQ
    TTS_id = selectedIndex(ui.id_2); //TTS
    Sex_id = selectedIndex(ui.id_3);//属性
    stg.put("QQ_id", QQ_id);
    stg.put("TTS_id", TTS_id);
    stg.put("sex", Sex_id);
}

function stop() {
    if (mt) {
        mt.interrupt();
        threads.shutDownAll();
        floaty.closeAll();
        setTimeout(function() {
            if (mt.isAlive()) {
                toast("停止失败");
                return;
            }
            toast("已停止");
            mt = null;
            ui.run(function() {
                ui.btn_start.text("启动");
            });
        }, 300);
    }
}

function start() {
    if (mt) {
        stop();
        return;
    }
    mt = threads.start(floa);
    ui.run(function() {
        ui.btn_start.text("停止");
    });
}